package com.spring.nbrbt.tools.otherutil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;

import com.spring.security.web.dao.JedisCache;

public class RedisCacheClient {
	
	private static JedisCache jedisCache = SpringContextHolder.getBean(JedisCache.class);
	
	public static void set(String sessionId, Session session) {
		jedisCache.append(sessionId, serialize(session));
	}

	public static void replace(String sessionId, Session session) {
		set(sessionId, session);

	}

	public static void delete(String sessionId) {
		jedisCache.del(sessionId);
	}

	public static Object get(String sessionId) {
		Object obj = deserialize(jedisCache.get(sessionId));
		return obj;
	}

	private static Object deserialize(String str) {
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			bis = new ByteArrayInputStream(Base64.decode(str));
			ois = new ObjectInputStream(bis);
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException("deserialize session error", e);
		} finally {
			try {
				ois.close();
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private static String serialize(Object obj) {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			return Base64.encodeToString(bos.toByteArray());
		} catch (Exception e) {
			throw new RuntimeException("serialize session error", e);
		} finally {
			try {
				oos.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}


}
